// 用户状态管理 - 简化版
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getPrefixName } from '@/config'
import { login as loginApi, register as registerApi, getUserInfo as getUserInfoApi } from '@/api/login/index'
import { useSimpleStorage } from '@/hooks/useStore'

export default defineStore(getPrefixName('user'), () => {
    // 持久化存储的token
    const { value: token, setValue: setToken, reset: resetToken } = useSimpleStorage('user_token', '')

    // 用户信息和加载状态
    const userInfo = ref({})
    const loading = ref(false)

    // 计算属性
    const checkLogin = computed(() => token.value !== '')

    // 登录方法
    const login = async (params: { account: string; password: string }) => {
        loading.value = true
        try {
            const res = await loginApi(params)
            setToken(res.data.token || '')
            // 登录成功后获取用户信息
            await getUserInfo()
            return res
        } catch (error) {
            throw error
        } finally {
            loading.value = false
        }
    }

    // 注册方法
    const register = async (params: { phone: string; password: string; code: string; resetpassword: string; superior_phone: string }) => {
        loading.value = true
        try {
            const res = await registerApi(params)
            setToken(res.data.token || '')
            // 注册成功后获取用户信息
            await getUserInfo()
            return res
        } catch (error) {
            throw error
        } finally {
            loading.value = false
        }
    }

    // 获取用户信息 - 这里调用 /api/member/member 接口
    const getUserInfo = async () => {
        loading.value = true
        try {
            const res = await getUserInfoApi()
            userInfo.value = res.data?.basic_info || res.data || {}
            return res
        } catch (error) {
            console.error('获取用户信息失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    // 退出登录
    const logOut = () => {
        resetToken()
        userInfo.value = {}
        uni.clearStorageSync()

        uni.showToast({
            icon: 'none',
            title: '退出成功',
            mask: true,
            success() {
                setTimeout(() => uni.reLaunch({ url: '/pages/index/index' }), 1000)
            }
        })
    }

    return {
        token,
        userInfo,
        loading,
        checkLogin,
        login,
        register,
        getUserInfo,
        logOut
    }
})
